package com.leunpha.mini.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * User: leunpha
 * Date: 14-5-11
 * Time: 下午9:28
 */
public class StringUtils {
    public static boolean isEmpty(String value){
        return value == null || "".equals(value.trim());
    }

    public static boolean isNotEmpty(String value){
        return !isEmpty(value);
    }

    /**
     *
     * @param name
     * @return
     */
    public static String normalize(String name){
        if(isEmpty(name))return null;
        return name.replaceAll("\\\\","/");
    }

    //返回文件名称
    public static String getFileName(String value){
        if(isEmpty(value)){
            return null;
        }
        value = normalize(value);
        return value.substring(value.lastIndexOf("/")+1,value.length());
    }

    /**
     * 返回文件基本名称不带后缀名
     * @param value
     * @return
     */
    public static String getFileBaseName(String value){
        if(isEmpty(value)){
            return null;
        }
        value = normalize(value);
        return value.substring(value.lastIndexOf("/")+1,value.lastIndexOf("."));
    }


    /**
     * 字符串加密
     * @param value
     * @return
     */
    public static String encryption(String value){
        StringBuffer buffer = new StringBuffer();
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(value.getBytes());
            byte bytes[] = messageDigest.digest();
            for (int offset = 0, i; offset < bytes.length; offset++) {
                i = bytes[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buffer.append("0");
                buffer.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return buffer.toString();
    }
}
